<template>
  <div class="product-main-box">
    <div class="product-list-container">
      <scroller :pulldown-config="pulldownConfig" :pullup-config="pullupConfig" height="100%" lock-x scrollbar-y
                use-pullup use-pulldown
                @on-pullup-loading="loadMore" @on-pulldown-loading="refresh" :pullup-status.sync="pullupStatus"
                ref="scroller">
        <div class="product-list-box">
          <div class="img-box">
            <img :src="classImage">
          </div>
          <count-down :closetime="Timecount"></count-down>
          <div class="choose-time">请选择送餐日期</div>
          <tab class="active-time" active-color="#FFA500" bar-active-color="bar-active-color" animate>
            <tab-item @on-item-click="tabItemClick(index)" :disabled="item.state == 1" :selected="item.state == 2"
                      v-for="(item,index) in activeDay" :key="'activetime'+index">
              <div class="active-time-box">
                <p>{{item.weekday}}</p>
                <p>{{item.weekdate}}</p>
              </div>
            </tab-item>
          </tab>
          <div class="product-list">
            <product-item @show-popup="showPopup" :show-info="false" @del="delCart" @add="addCart" :product-no="index"
                          :product="item"
                          v-for="(item,index) in products" :key="'product'+index"></product-item>
          </div>
        </div>
      </scroller>
    </div>
    <div @click="hidePop" v-show="showPop" class="pop-container">
      <div class="pop-bg"></div>
      <img class="bigImg" :src="bigImage" alt="">
    </div>
    <div class="cart-container">
      <cart @show-pop-cart="showPopCart" @to-cart="toCart" :count="cartNum" :price="cartPrice"></cart>
    </div>
    <Popup v-model="isShowPopCart" is-transparent="true">
      <div class="popup-contanier">
        <div class="popup-header-box">
          <p>早范早餐</p>
          <div @click="clearCart" class="clear-cart-box">
            <img src="http://static.52letsgo.cn/zz/wechatimg/ic_recover.png" alt="">
            <p>清空购物车</p>
          </div>
        </div>
        <div class="popup-scroller-box">

          <div>
            <div v-for="(item,index) in popCarts" :key="'popcart'+index">
              <div class="popup-cart-item">
                <div class="popup-product-info">
                  <p>{{item.name}}</p>
                  <p>{{item.date+"-"+item.week}}</p>
                </div>

                <div class="popup-product-count-box">
                  <p class="money">{{item.totalPrice | currency }}</p>
                  <img @click="popCartSub(index,item.productId,item.date)"
                       src="./../../images/ic_pop_cart_sub.png"
                       alt="">
                  <p>{{item.num}}</p>
                  <img @click="popCartAdd(index,item.productId,item.date)"
                       src="./../../images/ic_pop_cart_add.png"
                       alt="">
                </div>
              </div>
              <div class="line"></div>
            </div>
          </div>
        </div>
        <div class="cart-container">
          <cart @show-pop-cart="showPopCart" @to-cart="toCart" :count="cartNum" :price="cartPrice"></cart>
        </div>
      </div>
    </Popup>
  </div>
</template>
<script>
  import {MyGetWithToast, MyGet} from './../../commons/js/MyRequest'
  import {setItem} from './../../commons/js/LocalStorageUtil'
  import {solveDate,fmoney} from './../../commons/js/utils'
  import {getCartStorage, addCartStorage, countCartNum, getTotalPrice, delCart,clearCartStorage} from './../../commons/js/Cart'
  import Scroller from './../../components/scroller/index.vue'
  import CountDown from './../components/product/count-down.vue'
  import Tab from './../../components/tab/tab.vue'
  import TabItem from './../../components/tab/tab-item.vue'
  import ProductItem from './../components/product/product-item.vue'
  import Cart from './../components/menu/cart.vue'
  import Popup from './../../components/popup/index.vue'
  export default{
    data(){
      return {
        pullupEnabled: true,
        pullupStatus: 'default',
        pageNo: 0,
        pageSize: 10,
        pulldownConfig: {
          content: '下拉刷新',
          downContent: '松开进行加载',
          upContent: '下拉刷新',
          loadingContent: '加载中...',
          height: 30
        },
        pullupConfig: {
          content: '上拉加载更多',
          downContent: '松开进行加载',
          upContent: '上拉加载更多',
          loadingContent: '加载中...'
        },
        classImage: '',
        Timecount: 0,
        classId: '',
        classImage: '',
        closetime: '',
        activeDay: [],
        products: [],
        cartNum: 0,
        cartPrice: 0,
        isShowPopCart:false,
        popCarts:[],
        showPop:false
      }
    },
    components: {
      Scroller,
      CountDown,
      Tab,
      TabItem,
      ProductItem,
      Cart,
      Popup
    },
    mounted(){
      this.classId = this.$route.query.classId;
      this.closetime = this.$route.query.closetime;
      this.classImage = this.$route.query.classImage;
      this.$refs.scroller.reset();
      this.setCountDown();
      this.getActiveDay();
      this.getProducts();
      this.initCart();
    },
    methods: {
      loadMore(){
        //加载更多
        this.pageNo++;
        if (this.moreData) {
          var data = {
            action: "productType",
            classId: this.classId,
            begin: (this.pageNo * this.pageSize),
            end: this.pageSize
          };
          MyGet("ProductList", this, function (result, that) {
            console.log(result);
            var pdata = result.data;
            var oldData = that.products;
            var carts = getCartStorage();
            if (pdata.length < that.pageSize) {
              that.moreData = false;
            }
            for (var i = 0; i < pdata.length; i++) {
              pdata[i].type = "product-cell-3";
              pdata[i].productNo = 0;
              var num = 0;
              for (var j = 0; j < carts.length; j++) {
                if (carts[j].productId == pdata[i].id && carts[j].date == that.currentDate) {
                  num = carts[j].num;
                  break;
                }
              }
              pdata[i].cartNum = num;
              that.products.push(pdata[i]);
            }
            that.$nextTick(() => {
              that.$refs.scroller.donePullup();
              that.$refs.scroller.reset()
            });
          }, data);
        } else {
//          Global.showToast("没有更多数据啦", this);
          this.$nextTick(() => {
            this.$refs.scroller.donePullup();
            this.$refs.scroller.reset({
              bottom:0
            });
          })
        }


      },
      refresh(){
        this.pageNo = 0;
        this.getProducts();
      },
      setCountDown(){
        var date1 = new Date();  //开始时间
        var year = date1.getFullYear();
        var month = (date1.getMonth() + 1);
        var day = date1.getDate();
        var c_timeArr = this.closetime.split(":");
        var date2 = new Date(year, month, day, c_timeArr[0], c_timeArr[1], c_timeArr[2]);    //结束时间
        var date3 = date2.getTime() - date1.getTime();
        //计算出小时数

        var leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
        var hours = Math.floor(leave1 / (3600 * 1000))
        //计算相差分钟数
        var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
        var minutes = Math.floor(leave2 / (60 * 1000))
        var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        var seconds = Math.round(leave3 / 1000)

        var leave4 = Math.round(date3 / 1000);
        this.Timecount = (hours + ":" + minutes + ":" + seconds);
        console.log("productListTime:" + this.Timecount)
      },
      tabItemClick(index){
        this.currentDate = this.activeDay[index].wdate;
        this.currentDay = this.activeDay[index].wday;
        this.initProduct();
      },
      getActiveDay(){
        var data = {
          action: "hotelWeekday"
        };
        MyGetWithToast("ActiveDay", this, function (result, that) {
          console.log(result);
          var data = result.data;
          for (var i = 0; i < data.length; i++) {
            var date = data[i].wdate.substr(5);
            data[i].weekdate = date;
            data[i].weekday = solveDate(data[i].wday);
            if (data[i].state == 2) {
              that.currentDate = data[i].wdate;
              that.currentDay = data[i].wday;
            }
          }
          that.activeDay = data;
          this.$nextTick(() => {
            this.$refs.scroller.reset()
          })
        }, data);
      },
      getProducts(){
        this.products = new Array();
        this.moreData = true;
        var data = {
          action: "productType",
          classId: this.classId,
          begin: (this.pageNo * this.pageSize),
          end: this.pageSize
        };
        MyGetWithToast("ProductList", this, function (result, that) {
          console.log(result);
          var pdata = result.data;
          var oldData = that.products;
          var carts = getCartStorage();
          if (pdata.length < that.pageSize) {
            that.moreData = false;
          }
          var products = that.products;
          for (var i = 0; i < pdata.length; i++) {
            pdata[i].type = "product-cell-3";
            pdata[i].productNo = 0;
            var num = 0;
            for (var j = 0; j < carts.length; j++) {
              if (carts[j].productId == pdata[i].id && carts[j].date == that.currentDate) {
                num = carts[j].num;
                break;
              }
            }
            pdata[i].cartNum = num;
            products.push(pdata[i]);
          }
          that.products = products;
          that.$nextTick(() => {
            that.$refs.scroller.reset();
            that.$refs.scroller.donePulldown();
          })
        }, data);
      },
      showPopup(index, url){
        this.showPop = true;
        this.bigImage = url;
      },
      delCart(index){
        var num = this.products[index].cartNum;
        num--;
        this.products[index].cartNum = num;
        var id = this.products[index].id;
        var date = this.currentDate;
        delCart(id, date);
        this.initCart();
      },
      addCart(index){
        var num = this.products[index].cartNum;
        num++;
        this.products[index].cartNum = num;
        var date = this.currentDate;
        var day = this.currentDay;
        console.log("当前时间：" + date + "-" + day);
        addCartStorage(this.products[index], date, day);
        this.initCart();
      },
      initCart(){
        this.cartPrice = getTotalPrice();
        this.cartNum = countCartNum();
      },
      showPopCart(){
        this.isShowPopCart = true;
        var carts = getCartStorage();
        this.popCarts = carts;
      },
      hidePop(){
        this.showPop = false;
      },
      toCart(){
        console.log("去支付");
        this.$router.push("/cart");
      },
      initProduct(){
        var carts = getCartStorage();
        for (var i = 0; i < this.products.length; i++) {
          var num = 0;
          for (var j = 0; j < carts.length; j++) {
            if (carts[j].productId == this.products[i].id && carts[j].date == this.currentDate) {
              num = carts[j].num;
              break;
            }
          }
          this.products[i].cartNum = num;
        }
      },
      popCartAdd(index, id, date){
        var num = this.popCarts[index].num;
        this.popCarts[index].num++;
        this.popCarts[index].totalPrice = (this.popCarts[index].price * this.popCarts[index].num);
        addCart(id, date);
        this.initProduct();
        this.initCart();
      },
      popCartSub(index, id, date){
        var num = this.popCarts[index].num;
        if (num > 1) {
          this.popCarts[index].num--;
          this.popCarts[index].totalPrice = (this.popCarts[index].price * this.popCarts[index].num);
        } else {
          this.popCarts.splice(index, 1);
          if (this.popCarts.length <= 0) {
            this.isShowPopCart = false;
          }
        }
        delCart(id, date);
        this.initProduct();
        this.initCart();
      },
      clearCart(){
        clearCartStorage();
        this.initCart();
        this.initProduct();
        this.isShowPopCart = false;
      }
    },
    filters: {
      currency: function (value) {
        value = fmoney(value, 2);
        return ("¥" + value)
      }
    }
  }
</script>
<style lang="less">
  @import "productList.less";
</style>
